import EsriJSON from "ol/format/EsriJSON";
import { Feature } from "ol";
import { Geometry } from "ol/geom";

export const BASE_URL =
  "http://172.24.10.17:18300/1314361730/geoscene/rest/services/CIM/zhsl0723/MapServer";
export const API_KEY = "d58b17638488401192fb1ea7929ea795";

// 定义图层的类型
interface Layer {
  id: number;
  name: string;
}

// 主函数，用于执行查询操作
export async function executeFeatureQuery(layerName: string): Promise<Feature<Geometry>[]> {
  console.log("图层名", layerName);
  try {
    const layerId = await fetchLayerId(BASE_URL, API_KEY, layerName);
    console.log("图层id", layerId);
    const queryUrl = `${BASE_URL}/${layerId}/query?key=${API_KEY}`;
    const features = await fetchArcgisFeatures(queryUrl, "1=1", null);
    return features;
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}

// 获取指定图层名称的 ID
export async function fetchLayerId(baseUrl: string, apiKey: string, layerName: string): Promise<number> {
  const url = `${baseUrl}?f=json&key=${apiKey}`;
  try {
    const response = await fetch(url, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    const layers: Layer[] = data.layers;
    const targetLayer = layers.find((layer) => layer.name === layerName);
    if (targetLayer) {
      return targetLayer.id;
    } else {
      throw new Error(`Layer with name ${layerName} not found`);
    }
  } catch (error) {
    console.error("Error fetching layer ID:", error);
    throw error;
  }
}

// 查询 ArcGIS 要素
export async function fetchArcgisFeatures(
  url: string,
  filter: string,
  geometry: Geometry | null
): Promise<Feature<Geometry>[]> {
  const esriFormat = new EsriJSON();
  const paramsObj: Record<string, string> = {
    f: "json",
    where: filter,
    outFields: "*",
    returnGeometry: "true",
    geometryType: geometry ? "esriGeometryPolygon" : "esriGeometryEnvelope",
    spatialRel: "esriSpatialRelIntersects",
  };
  
  // 只有在 geometry 存在时才添加它
  if (geometry) {
    paramsObj.geometry = JSON.stringify(geometry);
  }

  const params = new URLSearchParams(paramsObj);

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: params.toString(),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return esriFormat.readFeatures(data);
  } catch (error) {
    console.error("Error fetching ArcGIS features:", error);
    throw error;
  }
}
